/*
esp8266
NodeMCU Flash闪存文件实现服务器
2021-09-12
*/

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WebServer.h>
#include <FS.h>

ESP8266WiFiMulti wifiMulti;

ESP8266WebServer esp8266_server(80); // 网络服务器http服务器对象，端口80

void setup()
{
  Serial.begin(9600);       // 启动中口
  
  wifiMulti.addAP("TPLeeSZ","2021#@Lee.com"); // 通过addAP添加wifi密码记录
  wifiMulti.addAP("TPLee2","6515304*eeL");
  wifiMulti.addAP("TPLee3","6515304*eeL");
  wifiMulti.addAP("TPLee","6515304*eeL");
  
  Serial.print("Connecting ... ");
  int i = 0;
  while(wifiMulti.run() != WL_CONNECTED) // wifiMulti.run()是重点，通过wifi环境中搜索addAP函数所存储的WiFi，成功为WL_CONNECTED
  {
    delay(1000);    // 1秒重试1次
    Serial.print(".");  
  }

  Serial.println("\n");
  Serial.print("Connected to "); // 连接成功
  Serial.println(WiFi.SSID());    // 连接的wifi名称
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP()); // 返回NodeMCU的IP地址

  if(SPIFFS.begin()) // 启动闪存文件系统
  {
    Serial.println("SPIFFS started");
  }
  else
  {
    Serial.println("SPIFFS failured to start");
  }

  // 启动网络服务功能
  esp8266_server.onNotFound(handleRequest); // 404响应统一处理请求
  esp8266_server.begin();
  Serial.println("HTTP esp8266_server started");
}

void handleRequest() // 处理请求访问
{
  String uri = esp8266_server.uri();
  bool handleStatus = handleFileResponse(uri);
  if(!handleStatus)
  {
    esp8266_server.send(404, "text/plain", "The page not found!(from ESP8266)");
  }
}

bool handleFileResponse(String path)
{
  if(path.endsWith("/"))
  {
    path = "/index.html"; // 首页
  }
  String contentType = getContentType(path);
  Serial.println(contentType);
  if(SPIFFS.exists(path)) // SPIFFS中是否存在文件
  {
    File file = SPIFFS.open(path, "r");
    esp8266_server.streamFile(file, contentType); // 返回文件响应
    file.close();
    return true;
  }
  Serial.printf("%s not exists.\n\n", path);
  return false;
}

String getContentType(String path)
{
  int extIndex = path.lastIndexOf(".");
  String ext = "";
  if(extIndex > -1)
  {
     ext = path.substring(extIndex+1);
     ext.toLowerCase();
  }
  String types[12][2] = {{"","text/plain"},{"html","text/html"},{"css","text/css"},{"js","text/js"},{"png","image/png"},{"gif","image/gif"},{"jpg","image/jpeg"},{"ico","image/x-icon"},{"xml","text/xml"},{"pdf","application/x-pdf"},{"zip","application/x-zip"},{"gz","application/x-gzip"}};
  Serial.println(ext);
  for(int i = 0; i < 12; ++i)
  {
    if(types[i][0] == ext)
    {
      return types[i][1];
    }
  }
  return types[0][1];
}

void loop()
{
  esp8266_server.handleClient(); // 处理http服务访问
}
